package com.wswy.wzcx.ui.car

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.text.*
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.ErrorCode
import com.wswy.wzcx.model.CarInfoModel
import com.wswy.wzcx.model.CarTypes
import com.wswy.wzcx.model.Converter
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.car.CarTypeData
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.base.CBaseActivity
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.car.choose.ChooseCarActivity
import com.wswy.wzcx.ui.car.result.QueryResultActivity
import com.wswy.wzcx.ui.dialog.Dialogs
import com.wswy.wzcx.ui.dialog.ImgDialog
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.dialog.WarningDialog
import com.wswy.wzcx.ui.keyboard.CarNoToolLayout
import com.wswy.wzcx.ui.other.TextWatcherIMPL
import com.wswy.wzcx.utils.FileUtils
import com.wswy.wzcx.utils.Tools
import com.wswy.wzcx.utils.fillText
import kotlinx.android.synthetic.main.activity_add_car_info.*
import timber.log.Timber
import kotlin.math.max

/**
 * 添加/修改 车辆，填写信息
 */
class AddCarInfoActivity : CBaseActivity() {

    companion object {

        private const val TAG = "AddCarInfoActivity"
        private const val EXTRA_CAR_INFO = "_extra.carinfo"
        private const val EXTRA_EDIT_CAR_INFO = "_extra.edit.carinfo"

        private const val REQUEST_CODE_DRIVING_LICENSE = 104
        private const val REQ_CHOOSE_CAR = 108

        private const val OCR_HASH = "extra.OcrHash"


        private val CAR_TYPES = arrayOf(
                Pair<String,String>("小型车",CarTypes.CAR_SMALL),
                Pair<String,String>("大型车",CarTypes.CAR_BIG),
                Pair<String,String>("摩托车",CarTypes.MOTO),
                Pair<String,String>("新能源(小车)",CarTypes.NE_CAR_SMALL),
                Pair<String,String>("新能源(大车)",CarTypes.NE_CAR_BIG)
                //Pair<String,String>("新能源",CarTypes.NE_CAR_SMALL)
                //Pair<String,String>("挂车","15")
        )


        fun start(context: Context, carInfoModel: CarInfoModel?) {

            Intent(context, AddCarInfoActivity::class.java).run {
                putExtra(EXTRA_CAR_INFO, carInfoModel)
                context.startActivity(this)
            }
        }

        fun edit(context: Context,userCarInfo: UserCarInfo){
            Converter.userCar2CarModel(userCarInfo).run {
                start(context,this)
            }
        }
    }

    private lateinit var carKeyboard: CarNoToolLayout
    private lateinit var addCarInfoViewModel: AddCarInfoViewModel

    private lateinit var mCarTypes:Array<String>
    private lateinit var mCarTypeIndexs:Array<String>
    private var currentCarType :String? = CarTypes.CAR_SMALL

    private var currentAutoCarType :String? = null

    //拍照弹窗
    private val carNoDiscernDialog: CarNoDiscernDialog by lazy {
        CarNoDiscernDialog(this).apply {

            onStartPhoto = {

                startActivityForResult(it, REQUEST_CODE_DRIVING_LICENSE)

                StatTools.sendClick(applicationContext, StatisticsId.clickOrcInNewAddCar)
            }
        }
    }
    //识别弹窗
    private val loadingDialog: LoadingDialog by lazy {
        LoadingDialog(this,"识别中")
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_car_info)

        addCarInfoViewModel = provideViewModel(AddCarInfoViewModel::class.java)
        addCarInfoViewModel.onCreate()

        //驾驶证拍照
        fl_camera.onClick {
            carNoDiscernDialog.show()
        }

        //选择车型
        ll_choose_car_type.onClick {
            showChooseCarType{

                tv_car_type.text = it.first
                currentCarType = it.second

               updateCarNoColor(false)

            }
        }

        //发动机号帮助
        img_engine_no_help.onClick {
            ImgDialog(this,R.drawable.pic_xingshizheng).show()
        }
        //车架号帮助
        img_frame_no_help.onClick {
            ImgDialog(this,R.drawable.pic_xingshizheng).show()
        }

        //查询
        btn_query.onClick {
            doQuery()
        }

        //选择车系
        ctl_choose_car_brand.onClick {
            StatTools.sendClick(applicationContext,StatisticsId.addcar_series)

            startActivityForResult(Intent(this,ChooseCarActivity::class.java),REQ_CHOOSE_CAR)
        }

        //选择车型
        ctl_choose_car_model.onClick {

            StatTools.sendClick(applicationContext,StatisticsId.addcar_type)

            startActivityForResult(ChooseCarActivity.getStartIntent(this,addCarInfoViewModel.carTypeData),REQ_CHOOSE_CAR)

        }

        //新违章提醒
        rl_new_f_notify.onClick {
            val tmp  = !switch_new_f_notify.isChecked
            if (tmp){
                showNotifyDialog()
            }else{
                switch_new_f_notify.toggle()

                addCarInfoViewModel.subscribeNotify = switch_new_f_notify.isChecked
            }

        }

        if (addCarInfoViewModel.subscribeNotify){
            switch_new_f_notify.isChecked = addCarInfoViewModel.subscribeNotify
        }


        //点击省份
        tv_car_no_province.onClick {
            showKeyBoard(showProvince = true,view = et_car_no)
        }


        et_car_no.addTextChangedListener(object : TextWatcherIMPL(){

            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                //自动更新车辆类型
                if (s?.length == 7){
                    //新能源
                    val autoType = when(currentCarType){
//                        CarTypes.CAR_SMALL -> CarTypes.NE_CAR_SMALL
//                        CarTypes.CAR_BIG -> CarTypes.NE_CAR_BIG


                        CarTypes.CAR_SMALL,CarTypes.CAR_BIG -> CarTypes.NE_CAR_SMALL
                        else -> null
                    }
                    if (autoType != null){
                        currentAutoCarType = autoType
                        currentCarType = autoType
                        updateCarNoColor()
                    }else{
                        currentAutoCarType = null
                    }
                }
            }

        })

        var first = true



        val etTouchListener = View.OnTouchListener { v, event ->
//            if (event.actionMasked == MotionEvent.ACTION_DOWN){
//                showKeyBoard(view = v)
//            }
//            false

            (v as? EditText)?.run {
                val oldType = inputType
                inputType = InputType.TYPE_NULL
                onTouchEvent(event)
                inputType = oldType
                showKeyBoard(view = v)
            }

            true
        }

        et_car_no.setOnTouchListener(etTouchListener)
        et_engine_no.setOnTouchListener(etTouchListener)
        et_frame_no.setOnTouchListener(etTouchListener)




        insertRequired(tv_car_no_hint,tv_engine_no_hint,tv_frame_no_hint)

        intent?.getParcelableExtra<CarInfoModel?>(EXTRA_CAR_INFO)?.let {

            if (!TextUtils.isEmpty(it.carId)){

                it.carId.toIntOrNull()?.run {
                    //修改模式
                    setAppTitle("编辑车辆")
                    btn_query.text = "保存"
                    btn_delete.visibility = View.VISIBLE

                    //删除
                    btn_delete.setOnClickListener {

                        val carId = this

                        AlertDialog.Builder(it.context).apply {

                            setTitle(R.string.alert)

                            setMessage("确认删除吗？")

                            setNegativeButton(R.string.cancel,null)

                            setPositiveButton(R.string.ok){_,_ ->
                                //删除
                                doDelete(carId)

                            }

                        }.run {
                            show()
                        }



                    }
                    //修改
                    btn_query.setOnClickListener {
                        doUpdate(this)
                    }
                }
            }else{
                setAppTitle("填写信息")
            }
            addCarInfoViewModel.sendOcrResult = it.ocrResult

            if (TextUtils.isEmpty(it.carNo)){
                et_car_no.requestFocus()
            }else if (TextUtils.isEmpty(it.frameNo)){
                et_frame_no.requestFocus()
            }else if (TextUtils.isEmpty(it.engineNo)){
                et_engine_no.requestFocus()
            }

            fillCarInfo(it)
        }?:kotlin.run {
            setAppTitle("填写信息")
        }

        listenerObservers()

        et_car_no.postDelayed({
            first = false
        },500)
    }

    private fun showNotifyDialog(){

        Dialogs.showSubscribePrivacy(this){
            this@AddCarInfoActivity.switch_new_f_notify?.runCatching {
                //isChecked = !isChecked
                toggle()
                if (isChecked){

                    Tools.getSp().putBoolean(DataCenter.KEY_SUBSCRIBE_NOTIFY,true)
                }
                addCarInfoViewModel.subscribeNotify = true
            }
        }

    }

    private fun listenerObservers(){

        //识别结果
        addCarInfoViewModel.getOcrResultLiveData().observe(this, Observer {
            it?.let { data ->

                if (data.inLoading()) {

                    loadingDialog.startLoading("识别中")

                } else if (data.isOk()) {




                    loadingDialog.let { dialog ->

                        if (data.data?.ocrSuccess() == true){

                            addCarInfoViewModel.sendOcrResult = data.data.ocrItems

                            dialog.setOnDismissListener { _ ->
                                carNoDiscernDialog.dismiss()

                                fillCarInfo(data.data.convert2CarInfo())

                            }
                            dialog.setSuccess("识别成功")
                        }else{
                            dialog.setSuccess("识别失败")
                        }
                    }

                } else {
                    loadingDialog.setSuccess(data.message)
                }


            }
        })

        //新增查询

        addCarInfoViewModel.getAddCarLiveData().observe(this, Observer {

            it?.run {

                intent?.removeExtra(OCR_HASH)

               if (inLoading()){
                   loadingDialog.startLoading("查询中")
               }else if (isOk()){


                   loadingDialog.setOnDismissListener {

                       if (data?.userCarInfo != null){
                           QueryResultActivity.start(this@AddCarInfoActivity, data, -1)
                           finish()
                       }else if (data?.errorCode == ErrorCode.ERROR_CAR_INFO){
                           //发动机号错误
                           val msg = data.errorMsg?:"车牌号与发动机号不一致"
                           ToastUtils.showText(msg)
                       }
                   }
                   loadingDialog.dismiss()

               }else{
                   loadingDialog.setSuccess("查询失败")
                   ToastUtils.showText(message)
               }
            }


        })

        //修改信息
        addCarInfoViewModel.getUpdateLiveData().observe(this, Observer {
            it?.run {

                intent?.removeExtra(OCR_HASH)

                if (inLoading()){
                    loadingDialog.startLoading("处理中")
                }else if (isOk()){
                    loadingDialog.setOnDismissListener {
                        QueryResultActivity.start(this@AddCarInfoActivity, data, -1)
                        finish()
                    }
                    loadingDialog.dismiss()
                }else{
                    loadingDialog.setSuccess(message)
                }
            }
        })

        //删除车辆
        addCarInfoViewModel.getDeleteLiveData().observe(this, Observer {
            it?.run {

                if (inLoading()){
                    loadingDialog.startLoading("处理中")
                }else if (isOk()){
                    loadingDialog.setOnDismissListener {
                        finish()
                    }
                    loadingDialog.setSuccess("删除成功")
                }else{
                    loadingDialog.setSuccess(message)
                }
            }
        })


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK){

            when(requestCode){
                REQUEST_CODE_DRIVING_LICENSE -> {
                    //拍照完成
                    addCarInfoViewModel.scannerOCR(FileUtils.getSaveFile(applicationContext).absolutePath)
                }

                REQ_CHOOSE_CAR -> {
                    //车辆选择完成
                    data?.getParcelableExtra<CarTypeData?>(Constants.EXTRA_DATA_CHOOSE_CAR)?.let {
                        updateCarTypeInfo(it)
                    }

                }
            }

        }


    }


    override fun onBackPressed() {
        //返回，键盘显示情况下先隐藏
        if (::carKeyboard.isInitialized && carKeyboard.isShowing()) {
            carKeyboard.hide()
        } else {
            super.onBackPressed()
        }
    }

    private fun showKeyBoard(showProvince:Boolean = false,view: View) {
        if (!::carKeyboard.isInitialized) {
            //延迟加载键盘
            viewstub_keyboard.inflate()

            carKeyboard = findViewById(R.id.ll_keyboard)

            carKeyboard.onHideCallback = {
                //currentFocus?.clearFocus()
            }

            carKeyboard.provincesClick = {
                tv_car_no_province.text = it
            }

            carKeyboard.alphabetClick = { alphabet ->

                //几个输入框的最大可输入长度
                val len = when (currentFocus) {
                    et_car_no -> 7
                    et_engine_no -> 16
                    et_frame_no -> 17
                    else -> 0
                }
                carKeyboard.append(currentFocus, alphabet, len)
            }

            carKeyboard.deleteClick = {
                carKeyboard.delete(currentFocus, it)
            }

        }
        //只在输入车牌时显示可以却换地区，车架号等禁止切换地区
        carKeyboard.show(showProvince,disableChangeProvinces = view !== et_car_no)
    }

    private fun fillCarInfo(info:CarInfoModel?){
        info?.let {
            it.province?.run {
                tv_car_no_province.text = this
            }
            it.noWithoutProvince?.let {

                if (it.length == 7 && info.carType?.startsWith("5") != true){
                    //新能源车，更正
                    info.carType = CarTypes.NE_CAR_SMALL
                }

                et_car_no.fillText(it)
            }

            et_engine_no.fillText(it.engineNo)
            et_frame_no.fillText(it.frameNo)

            //保存ocr id
            intent?.putExtra(OCR_HASH,it.ocrHash)

            (CAR_TYPES.firstOrNull { it.second == info.carType }?:CAR_TYPES[0]).let {
                tv_car_type.text = it.first
                currentCarType= it.second
            }

            updateCarNoColor(false)

            if (!TextUtils.isEmpty(it.series)){
                tv_car_series.text = it.series
            }
            if (!TextUtils.isEmpty(it.carId)){

                ctl_choose_car_model.visibility = View.VISIBLE
            }

            if (!TextUtils.isEmpty(it.series)){
                tv_car_model.text = it.model
            }
        }
    }

    private fun insertRequired(vararg textView: TextView){
        textView.forEach {
            it.text = SpannableStringBuilder(it.text).insert(0,SpannableString("* ").apply {
                setSpan(ForegroundColorSpan(Color.RED),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
            })
        }
    }

    private fun updateCarTypeInfo(chooseCarData: CarTypeData){
        //保存选择的车型
        addCarInfoViewModel.updateEdit(chooseCarData)


        chooseCarData.series?.let {
            //选择了车系
            val series:String?=chooseCarData.brand?.name +" " +chooseCarData.series?.name

            tv_car_series.text = series
            ctl_choose_car_model.visibility = View.VISIBLE
        }?:kotlin.run {
            //没有选择车系,隐藏车型
            tv_car_series.setText(R.string.choose_car_series)
            ctl_choose_car_model.visibility = View.GONE
        }

        chooseCarData.model?.let {
            tv_car_model.text = chooseCarData.model?.name
        }?:kotlin.run {
            tv_car_model.setText(R.string.choose_car_model)
        }

    }

    private fun doQuery(){
        //新增查询
        addCarInfoViewModel.carInfoModel.run {
            carNo = "${tv_car_no_province.text}${et_car_no.text?:""}"
            engineNo = et_engine_no.text?.toString()?:""
            frameNo = et_frame_no.text?.toString()?:""
            carType = currentCarType

        }

        if (addCarInfoViewModel.carInfoModel.carNo?.length?:0 < 7){
            ToastUtils.showText("请输入完整车牌号")
            return
        }

        if (TextUtils.isEmpty(addCarInfoViewModel.carInfoModel.engineNo)){
            ToastUtils.showText("发动机号不能为空")
            return
        }

        if (TextUtils.isEmpty(addCarInfoViewModel.carInfoModel.frameNo)){
            ToastUtils.showText("车架号不能为空")
            return
        }

        if (addCarInfoViewModel.carInfoModel.engineNo.length < 6){
            ToastUtils.showText("发动机号不正确")
            return
        }

        addCarInfoViewModel.carInfoModel.ocrHash = intent?.getStringExtra(OCR_HASH)


        addCarInfoViewModel.addCar(this)

        StatTools.sendClick(this, StatisticsId.clickQueryInNewAddCar)
    }


    private fun doDelete(carId:Int){
        //删除
        addCarInfoViewModel.deleteCar(carId)
    }

    private fun doUpdate(carId:Int){
        //修改车型信息
        addCarInfoViewModel.carInfoModel.run {
            carNo = "${tv_car_no_province.text}${et_car_no.text?:""}"
            engineNo = et_engine_no.text?.toString()
            frameNo = et_frame_no.text?.toString()
            carType = currentCarType

            ocrHash = intent?.getStringExtra(OCR_HASH)
        }


        if (addCarInfoViewModel.carInfoModel.carNo?.length?:0 < 7){
            ToastUtils.showText("请输入完整车牌号")
            return
        }

        if (TextUtils.isEmpty(addCarInfoViewModel.carInfoModel.engineNo)){
            ToastUtils.showText("发动机号不能为空")
            return
        }

        if (TextUtils.isEmpty(addCarInfoViewModel.carInfoModel.frameNo)){
            ToastUtils.showText("车架号不能为空")
            return
        }

        if (addCarInfoViewModel.carInfoModel.engineNo.length < 6){
            ToastUtils.showText("发动机号不正确")
            return
        }

        addCarInfoViewModel.updateCar(carId)
    }


    private fun showChooseCarType(block:((Pair<String,String>)->Unit)){

        if (!this::mCarTypes.isInitialized){
            mCarTypes = CAR_TYPES.map { it.first }.toTypedArray()
        }
        if (!this::mCarTypeIndexs.isInitialized){
            mCarTypeIndexs = CAR_TYPES.map { it.second }.toTypedArray()
        }

        AlertDialog.Builder(this).apply {

            setTitle("选择车辆类型")
            val st = arrayOf(max(mCarTypeIndexs.indexOfFirst { TextUtils.equals(it,currentCarType) },0))

            setSingleChoiceItems(mCarTypes,st[0]){ _, which ->
                st[0]=which
            }

            setPositiveButton(R.string.ok) { dialog, _ ->

                val idx = st[0]

                block.invoke(Pair(mCarTypes[idx],mCarTypeIndexs[idx]))

                dialog.dismiss()
            }

            setNegativeButton(R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }

        }.run {
            show()
        }
    }

    private fun updateCarNoColor(updateText:Boolean = true){
        addCarInfoViewModel.getCarNoColorConfig(currentCarType).run {
            tv_car_no_province.setBackgroundResource(bgResDrawable)
            et_car_no.setTextColor(textColor)

            if (updateText){
                (CAR_TYPES.firstOrNull { it.second == currentCarType }?:CAR_TYPES[0]).let {
                    tv_car_type.text = it.first
                }
            }

            if (currentCarType == CarTypes.NE_CAR_SMALL || currentCarType == CarTypes.NE_CAR_BIG){

                ContextCompat.getDrawable(this@AddCarInfoActivity,R.drawable.car_nengyuan)?.run {

                    setBounds(0,0,SizeUtils.dp2px(16f),SizeUtils.dp2px(16f))
                    tv_car_type.compoundDrawablePadding = SizeUtils.dp2px(10f)
                    tv_car_type.setCompoundDrawables(this,null,null,null)
                }
            }else{
                tv_car_type.setCompoundDrawables(null,null,null,null)
            }

        }
    }

}